import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
// import viteCompression from 'vite-plugin-compression'
// import { visualizer } from 'rollup-plugin-visualizer'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(),
    // Gzip压缩 - 暂时禁用，需要安装 vite-plugin-compression
    // viteCompression({
    //   verbose: true,
    //   disable: false,
    //   threshold: 10240, // 10KB以上文件压缩
    //   algorithm: 'gzip',
    //   ext: '.gz',
    // }),
    // // Brotli压缩
    // viteCompression({
    //   verbose: true,
    //   disable: false,
    //   threshold: 10240,
    //   algorithm: 'brotliCompress',
    //   ext: '.br',
    // }),
    // // Bundle分析（可选，仅在需要时启用）
    // process.env.ANALYZE === 'true' && visualizer({
    //   filename: './dist/stats.html',
    //   open: true,
    //   gzipSize: true,
    //   brotliSize: true,
    // }),
  ].filter(Boolean),
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 13000,
    host: true,
    // 允许的主机名
    allowedHosts: [
      'localhost',
      '127.0.0.1',
      '50593jm674la.vicp.fun',
      '.vicp.fun', // 允许所有 .vicp.fun 子域名
      'www.xjxd100.com',
      '.xjxd100.com', // 允许所有 .xjxd100.com 子域名
    ],
    proxy: {
      // AI生成API - 代理到8002端口 (新增)
      '^/ai/.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying AI API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ AI API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ AI API proxy error:', err.message);
          });
        },
      },
      // 热点内容生成API - 代理到8002端口
      '^/api/v1/hot-content.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying hot-content API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ Hot-content API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ Hot-content API proxy error:', err.message);
          });
        },
      },
      // 模型配置API - 代理到8002端口
      '^/api/v1/model.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying model API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ Model API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ Model API proxy error:', err.message);
          });
        },
      },
      // 文件上传API - 代理到8002端口
      '^/api/v1/files.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying file API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ File API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ File API proxy error:', err.message);
          });
        },
      },
      // 模板API - 代理到8002端口
      '^/api/v1/templates.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying template API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ Template API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ Template API proxy error:', err.message);
          });
        },
      },
      // AI提示生成API - 代理到8002端口
      '^/api/v1/ai.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying AI hints API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ AI hints API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ AI hints API proxy error:', err.message);
          });
        },
      },
      // 头脑风暴API - 代理到8002端口
      '^/api/v1/brainstorm.*': {
        target: 'http://127.0.0.1:8002',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying brainstorm API request:', req.method, req.url, '-> http://127.0.0.1:8002');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ Brainstorm API response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ Brainstorm API proxy error:', err.message);
          });
        },
      },
      // 热点数据API - 代理到8001端口
      '^/api/v1/hot-items.*': {
        target: 'http://127.0.0.1:8001',
        changeOrigin: true,
        secure: false,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (_proxyReq, req, _res) => {
            console.log('🔄 Proxying crawler API request:', req.method, req.url, '-> http://127.0.0.1:8001');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('✅ Proxy response:', proxyRes.statusCode, req.url);
          });
          proxy.on('error', (err, _req, _res) => {
            console.log('❌ Proxy error:', err.message);
          });
        },
      },
      '^/api/v1/cors-test': {
        target: 'http://172.22.206.187:8001',
        changeOrigin: true,
      },
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
      },
      '/ws': {
        target: 'ws://localhost:8000',
        ws: true,
        changeOrigin: true,
      },
      // WebSocket for Brainstorm and Copilot
      '^/ws/brainstorm': {
        target: 'ws://127.0.0.1:8002',
        ws: true,
        changeOrigin: true,
      },
      '^/ws/copilot': {
        target: 'ws://127.0.0.1:8002',
        ws: true,
        changeOrigin: true,
      },
    },
  },
  define: {
    'process.env': {},
    global: 'globalThis',
  },
  envPrefix: ['VITE_', 'REACT_APP_'],
  build: {
    // Performance optimizations
    target: 'es2015',
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    // Code splitting for better caching
    rollupOptions: {
      output: {
        manualChunks(id) {
          // 将 node_modules 中的代码单独打包
          if (id.includes('node_modules')) {
            // React核心库
            if (id.includes('react') || id.includes('react-dom') || id.includes('react-router')) {
              return 'react-vendor';
            }
            // Ant Design UI库
            if (id.includes('antd') || id.includes('@ant-design')) {
              return 'antd-vendor';
            }
            // Monaco Editor（大型库，单独拆分）
            if (id.includes('@monaco-editor') || id.includes('monaco-editor')) {
              return 'editor-vendor';
            }
            // ECharts图表库（大型库，单独拆分）
            if (id.includes('echarts') || id.includes('echarts-for-react')) {
              return 'chart-vendor';
            }
            // Markdown相关
            if (id.includes('react-markdown') || id.includes('remark') || id.includes('rehype')) {
              return 'markdown-vendor';
            }
            // 其他第三方库
            return 'vendor';
          }
        },
      },
    },
    // Chunk size warnings
    chunkSizeWarningLimit: 500,
    // Source map for production
    sourcemap: false,
    // Assets inlining threshold
    assetsInlineLimit: 4096,
  },
  optimizeDeps: {
    // Pre-bundle heavy dependencies for faster dev startup
    include: [
      'react',
      'react-dom',
      'react-router-dom',
      'antd',
      '@ant-design/icons',
      'zustand',
      'axios',
      'react-markdown',
      'dayjs',
    ],
    // 强制预构建这些模块，加快首次加载
    force: false,
  },
  // CSS optimization
  css: {
    modules: {
      localsConvention: 'camelCaseOnly',
    },
  },
})
